import {
  downloadGigaResource,
  getGigaResourcePermission,
  getProductBaseInfo,
  getProductDocumentHTML,
  getProductPriceInfo,
  GetProductPriceInfoResult,
} from '@/api/giga';
import config, { MessageType } from '@/config';
import { AccountSetting } from '@/store';
import { useProxyStore } from '@/store/proxy';
import { toast } from 'sonner';
import { ProductInfo } from './dianxiaomi';
import { getProxyUrls, setProxyDirect, setProxyPAC } from './proxy';

// 获取 arg1 参数
export function getArg1(loginDocument: Document) {
  try {
    const scriptEle = loginDocument.scripts[0];
    const textContext = scriptEle.textContent;
    if (textContext) {
      const match = textContext.match(/arg1\s*=\s*'([^']+)'/);
      if (match && match[1]) {
        return match[1];
      }
    }
  } catch (error) {
    return '';
  }
  return '';
}

// rc4 解密算法
export function rc4Decrypt(base64Data: string, key: string) {
  // 初始化RC4算法所需变量
  let sBox = []; // S盒（状态数组）
  let j = 0; // 临时索引
  let temp; // 交换临时变量
  let decrypted = ''; // 解密结果

  // Step 1: 处理Base64输入数据
  try {
    // 解码Base64并转换为URL编码格式的二进制字符串
    const decodedData = atob(base64Data);
    let urlEncoded = '';
    for (let i = 0; i < decodedData.length; i++) {
      // 将每个字节转换为 %XX 形式（如 0x1A → %1A）
      const hex = ('00' + decodedData.charCodeAt(i).toString(16)).slice(-2);
      urlEncoded += '%' + hex;
    }
    // 转换为可处理的字符串（兼容二进制）
    const processedData = decodeURIComponent(urlEncoded);

    // Step 2: 初始化S盒（KSA阶段）
    for (let i = 0; i < 256; i++) {
      sBox[i] = i;
    }

    // 使用密钥打乱S盒
    for (let i = 0; i < 256; i++) {
      j = (j + sBox[i] + key.charCodeAt(i % key.length)) % 256;
      // 交换sBox[i]和sBox[j]
      temp = sBox[i];
      sBox[i] = sBox[j];
      sBox[j] = temp;
    }

    // Step 3: 生成密钥流并解密（PRGA阶段）
    let i = 0;
    j = 0;
    for (let n = 0; n < processedData.length; n++) {
      i = (i + 1) % 256;
      j = (j + sBox[i]) % 256;

      // 交换sBox[i]和sBox[j]
      temp = sBox[i];
      sBox[i] = sBox[j];
      sBox[j] = temp;

      // 计算密钥流字节并异或解密
      const keyStreamByte = sBox[(sBox[i] + sBox[j]) % 256];
      decrypted += String.fromCharCode(processedData.charCodeAt(n) ^ keyStreamByte);
    }

    return decrypted;
  } catch (error) {
    console.error('RC4解密失败:', error);
    return ''; // 返回空字符串或根据需求处理异常
  }
}

// 生成 acw_sc__v2 cookie 值
export function getAcwScV2(arg1: string) {
  var encodeString = [
    'csKHwqMI',
    'ZsKJwr8VeAsy',
    'UcKiN8O/wplwMA==',
    'JR8CTg==',
    'YsOnbSEQw7ozwqZKesKUw7kwX8ORIQ==',
    'w7oVS8OSwoPCl3jChMKhw6HDlsKXw4s/YsOG',
    'fwVmI1AtwplaY8Otw5cNfSgpw6M=',
    'OcONwrjCqsKxTGTChsOjEWE8PcOcJ8K6',
    'U8K5LcOtwpV0EMOkw47DrMOX',
    'HMO2woHCiMK9SlXClcOoC1k=',
    'asKIwqMDdgMuPsOKBMKcwrrCtkLDrMKBw64d',
    'wqImMT0tw6RNw5k=',
    'DMKcU0JmUwUv',
    'VjHDlMOHVcONX3fDicKJHQ==',
    'wqhBH8Knw4TDhSDDgMOdwrjCncOWwphhN8KCGcKqw6dHAU5+wrg2JcKaw4IEJcOcwrRJwoZ0wqF9YgAV',
    'dzd2w5bDm3jDpsK3wpY=',
    'w4PDgcKXwo3CkcKLwr5qwrY=',
    'wrJOTcOQWMOg',
    'wqTDvcOjw447wr4=',
    'w5XDqsKhMF1/',
    'wrAyHsOfwppc',
    'J3dVPcOxLg==',
    'wrdHw7p9Zw==',
    'w4rDo8KmNEw=',
    'IMKAUkBt',
    'w6bDrcKQwpVHwpNQwqU=',
    'd8OsWhAUw7YzwrU=',
    'wqnCksOeezrDhw==',
    'UsKnIMKWV8K/',
    'w4zDocK8NUZv',
    'c8OxZhAJw6skwqJj',
    'PcKIw4nCkkVb',
    'KHgodMO2VQ==',
    'wpsmwqvDnGFq',
    'wqLDt8Okw4c=',
    'w7w1w4PCpsO4wqA=',
    'wq9FRsOqWMOq',
    'byBhw7rDm34=',
    'LHg+S8OtTw==',
    'wqhOw715dsOH',
    'U8O7VsO0wqvDvcKuKsOqX8Kr',
    'Yittw5DDnWnDrA==',
    'YMKIwqUUfgIk',
    'aB7DlMODTQ==',
    'wpfDh8Orw6kk',
    'w7vCqMOrY8KAVk5OwpnCu8OaXsKZP3DClcKyw6HDrQ==',
    'wow+w6vDmHpsw7Rtwo98LC7CiG7CksORT8KlW8O5wr3Di8OTHsODeHjDmcKlJsKqVA==',
    'NwV+',
    'w7HDrcKtwpJawpZb',
    'wpQswqvDiHpuw6I=',
    'YMKUwqMJZQ==',
    'KH1VKcOqKsK1',
    'fQ5sFUkkwpI=',
    'wrvCrcOBR8Kk',
    'M3w0fQ==',
    'w6xXwqPDvMOFwo5d',
  ];
  const length = encodeString.length;
  const counter = 347;
  const ret = counter % length;
  for (let i = 0; i < ret; i++) {
    encodeString.push(encodeString.shift()!);
  }

  // @ts-ignore
  function _0x55f3(index: string, key: string) {
    // @ts-ignore
    index = parseInt(index, 16);
    // @ts-ignore
    let eStr = encodeString[index];
    // @ts-ignore
    if (!_0x55f3['data']) {
      // @ts-ignore
      _0x55f3['data'] = {};
    }
    // @ts-ignore
    if (_0x55f3['data'][index] === undefined) {
      eStr = rc4Decrypt(eStr, key);
      // @ts-ignore
      _0x55f3['data'][index] = eStr;
    } else {
      // @ts-ignore
      eStr = _0x55f3['data'][index];
    }
    return eStr;
  }

  function getDecodeString(key: string) {
    function hexXor(str1: string, str2: string) {
      var _0x5a5d3b = '';
      for (var index = 0; index < str1['length'] && index < str2['length']; index += 2) {
        // 把一个 16 进制字符串转换成十进制数字
        var _0x401af1 = parseInt(str1['slice'](index, index + 2), 16);
        var _0x105f59 = parseInt(str2['slice'](index, index + 2), 16);
        var _0x189e2c = (_0x401af1 ^ _0x105f59)['toString'](16);
        if (_0x189e2c['length'] == 1) {
          _0x189e2c = '0' + _0x189e2c;
        }
        _0x5a5d3b += _0x189e2c;
      }
      return _0x5a5d3b;
    }

    function unsbox(str: string) {
      var _0x4b082b = [
        0xf, 0x23, 0x1d, 0x18, 0x21, 0x10, 0x1, 0x26, 0xa, 0x9, 0x13, 0x1f, 0x28, 0x1b, 0x16, 0x17,
        0x19, 0xd, 0x6, 0xb, 0x27, 0x12, 0x14, 0x8, 0xe, 0x15, 0x20, 0x1a, 0x2, 0x1e, 0x7, 0x4,
        0x11, 0x5, 0x3, 0x1c, 0x22, 0x25, 0xc, 0x24,
      ];
      var _0x4da0dc = [];
      var _0x12605e = '';
      for (var index = 0x0; index < str['length']; index++) {
        var _0x385ee3 = str[index];
        for (var i = 0; i < _0x4b082b['length']; i++) {
          if (_0x4b082b[i] == index + 1) {
            _0x4da0dc[i] = _0x385ee3;
          }
        }
      }
      _0x12605e = _0x4da0dc['join']('');
      return _0x12605e;
    }

    var randomStr = _0x55f3('0x3', 'jS1Y');

    var _0x23a392 = unsbox(key);
    var arg2 = hexXor(_0x23a392, randomStr);
    return arg2;
  }

  return getDecodeString(arg1);
}

// 更新网站的 acw_sc__v2 cookie 值
export async function updateGigaAcwScV2CookieExtension(acwScV2: string) {
  await browser.cookies.set({
    url: 'https://www.gigab2b.com',
    name: 'acw_sc__v2',
    value: acwScV2,
    path: '/',
    expirationDate: Date.now() + 1000 * 60 * 60 * 24 * 365 * 10,
  });
}

export async function updateGigaAcwScV2CookieLocal(acwScV2: string) {
  const cookieName = 'acw_sc__v2';
  const cookieValue = acwScV2;
  const domain = 'www.gigab2b.com';
  const path = '/';
  const expirationDate = new Date(Date.now() + 1000 * 60 * 60 * 24 * 365 * 10).toUTCString();

  const cookieString = `${cookieName}=${encodeURIComponent(cookieValue)}; domain=${domain}; path=${path}; expires=${expirationDate}; SameSite=None; Secure`;

  document.cookie = cookieString;
}

// 读取产品在 gigab2b 中的信息
export interface GigaProductInfo {
  productName: string;
  feature?: string[];
  description?: Array<{
    name: string;
    value: string;
  }>;
}
export async function getGigaProductInfo(
  productInfo: ProductInfo,
  accountSetting: AccountSetting['giga'],
) {
  // if (!accountSetting.accessToken) {
  //   throw new Error(`没有获取到 giga 的 access_token,需要在账号设置中设置正确的账号信息`);
  // }
  const giga2bProductInfo = {} as GigaProductInfo;
  const detailResult = await browser.runtime.sendMessage({
    type: MessageType.getGiga2bProductInfo,
    data: {
      productId: productInfo.gigaProductId,
      sku: productInfo.gigaSku,
      accessToken: accountSetting.accessToken,
      tokenType: accountSetting.tokenType,
    },
  });
  console.log('Giga2bProductInfo', detailResult);
  if (detailResult.code === 0) {
    const data = detailResult.data;
    if (data) {
      // 填充产品名称
      giga2bProductInfo.productName = data.productName;

      // 处理 feature
      if (data.feature) {
        const feature: string[] = [];
        const div = document.createElement('div');
        div.innerHTML = data.feature;
        div.querySelectorAll('li').forEach((li) => {
          if (li.textContent) {
            feature.push(li.textContent);
          }
        });
        giga2bProductInfo.feature = feature;
      }
      // 处理 description
      if (data.description) {
        const description: {
          name: string;
          value: string;
        }[] = [];
        const div = document.createElement('div');
        div.innerHTML = data.description;
        div.querySelectorAll('table tr').forEach((tr) => {
          if (
            tr.querySelector('td:nth-child(1)')?.textContent &&
            tr.querySelector('td:nth-child(2)')?.textContent
          ) {
            description.push({
              name: tr.querySelector('td:nth-child(1)')?.textContent || '',
              value: tr.querySelector('td:nth-child(2)')?.textContent || '',
            });
          }
        });
        giga2bProductInfo.description = description;
      }
    }

    return giga2bProductInfo;
  } else {
    throw new Error(`${detailResult.msg}`);
  }
}

// 获取 giga 中的 sku 和 productId
export function getGigaSkuAndProductId(skuIdInfo: string) {
  return skuIdInfo.split(config.gigaDelimiter);
}

// 读取产品在 gigab2b 中的详细信息,这些信息主要用于采集
export interface GigaProductDetialInfo {
  // 产品的标题
  productName: string;

  // 产品的 id
  gigaProductId: string;

  // 产品的 item code
  gigaSku: string;

  // 产品的货号名称
  // item code [gg] gigaProductId
  skuIdInfo: string;

  // 产品的 url 页面
  // 例如 https://www.gigab2b.com/index.php?route=product/product&product_id=930922
  productUrl: string;

  // 基础价格
  // 单位精确到美分
  basePrice: number;

  // 履约价格
  // 单位精确到美分
  fulfillmentPrice: number;

  // 产品的总价格
  // 基础价格加上履约价格
  // 单位精确到美分
  totalPrice: number;

  // 包装后的长度(in)
  packageLength: string;

  // 包装后的宽度(in)
  packageWidth: string;

  // 包装后的高度(in)
  packageHeight: string;

  // 包装后的重量(lbs)
  packageWeight: string;

  // 主颜色
  // 用来填充变种属性的值
  mainColor: string;

  // 可以库存
  available: number;

  // 对应 Product Features
  // 也就是 characteristic 信息
  feature: string[];

  // 对应 Description 信息
  // 也就是 description 信息
  description: Array<{
    name: string;
    value: string;
  }>;
}
export async function getGigaProductDetailInfo({
  gigaProductId,
  gigaSku,
  skuIdInfo,
}: {
  gigaProductId: string;
  gigaSku: string;
  skuIdInfo: string;
}) {
  const gigaProductDetialInfo = {} as GigaProductDetialInfo;
  gigaProductDetialInfo.gigaProductId = gigaProductId;
  gigaProductDetialInfo.gigaSku = gigaSku;
  gigaProductDetialInfo.skuIdInfo = skuIdInfo;
  gigaProductDetialInfo.productUrl = `https://www.gigab2b.com/index.php?route=product/product&product_id=${gigaProductId}`;
  const productDetialInfo = await getProductBaseInfo(gigaProductId);
  console.log('giga 产品的基础信息', productDetialInfo);
  if (productDetialInfo.code === 200) {
    const productInfo = productDetialInfo.data.product_info;
    const feature = productInfo.characteristic;
    if (!feature) {
      throw new Error(`获取产品 feature 失败: 需要先登录到 giga 网站`);
    }
    gigaProductDetialInfo.productName = productInfo.product_name;

    // 填充尺寸信息
    const packageSize = productInfo.specification.package_size;
    if (Array.isArray(packageSize.general) && packageSize.general.length === 0) {
      const combo = packageSize.combo;
      if (Array.isArray(combo) && combo.length > 0) {
        const comboItem = combo[0];
        gigaProductDetialInfo.packageLength = comboItem.length;
        gigaProductDetialInfo.packageWidth = comboItem.width;
        gigaProductDetialInfo.packageHeight = comboItem.height;
        gigaProductDetialInfo.packageWeight = comboItem.weight;
      }
    } else {
      gigaProductDetialInfo.packageLength = packageSize.general.length;
      gigaProductDetialInfo.packageWidth = packageSize.general.width;
      gigaProductDetialInfo.packageHeight = packageSize.general.height;
      gigaProductDetialInfo.packageWeight = packageSize.general.weight;
    }

    // 填充变体
    const propertyInfos = productInfo.specification.property_infos;
    gigaProductDetialInfo.mainColor =
      propertyInfos.find((propertyInfo) => {
        return propertyInfo.property_name === 'Main Color';
      })?.property_value_name || '';

    gigaProductDetialInfo.feature = parseCharacteristic(productInfo.characteristic);
    gigaProductDetialInfo.description = parseDescription(productInfo.description);
  } else {
    throw new Error(`采集基础信息失败: ${productDetialInfo.msg}`);
  }

  // 开始采集库存和价钱等信息
  const productPriceInfo = await getProductPrice(gigaProductId);
  console.log('giga 产品的价格库存信息', productPriceInfo);
  if (productPriceInfo.code === 200) {
    const data = productPriceInfo.data;
    gigaProductDetialInfo.basePrice = data.base_price_info.price * 100;
    gigaProductDetialInfo.fulfillmentPrice = data.fulfillment_options.drop_ship.total_amount * 100;
    gigaProductDetialInfo.totalPrice =
      gigaProductDetialInfo.basePrice + gigaProductDetialInfo.fulfillmentPrice;
    gigaProductDetialInfo.available = data.quantity.quantity;
  } else {
    throw new Error(`采集价格库存信息失败: ${productPriceInfo.msg}`);
  }

  return gigaProductDetialInfo;
}

// 获取权限刷新的参数
export async function getGigaResourcePermissionParams(gigaProductId: string) {
  const html = await getProductDocumentHTML(gigaProductId);
  // 如果返回的是 acwScV2 页面需要生成 acwScV2 参数后重新访问
  const match = html.match(/arg1\s*=\s*'([^']+)'/);
  // 如果返回的是 arg1 页面进行增加 cookie 处理
  if (match && match[1]) {
    const arg1 = match[1];
    console.log(arg1);
    const acwScV2 = getAcwScV2(arg1);
    console.log('acwScV2', acwScV2);
    // 更新 cookie
    await updateGigaAcwScV2CookieLocal(acwScV2);
    return getGigaResourcePermissionParams(gigaProductId);
  } else {
    const productBaseInfo = await getProductBaseInfo(gigaProductId);
    let customerId = 0;
    let xCsrfToken = '';
    try {
      const imageUrl = productBaseInfo.data.product_info.image_list[0].popup;
      console.log(imageUrl);
      // @ts-ignore
      customerId = imageUrl.match(/wkseller\/(\d+)\//)[1];

      // @ts-ignore
      xCsrfToken = html.match(/X-CSRF-TOKEN\'\,\s+\'(\w+)/i)[1];
      console.log(xCsrfToken);
    } catch (error) {
      console.log(error);
    }
    return {
      customerId,
      xCsrfToken: xCsrfToken,
    };
  }
}

// 进行下载资源的权限刷新
export async function refreshGigaResourcePermission({ gigaProductId }: { gigaProductId: string }) {
  const { customerId, xCsrfToken } = await getGigaResourcePermissionParams(gigaProductId);
  const refreshGigaResourcePermissionResult = await getGigaResourcePermission({
    gigaProductId,
    customerId: customerId,
    xCsrfToken: xCsrfToken,
  });
  if (refreshGigaResourcePermissionResult.code !== 200) {
    throw new Error(`刷新下载资源权限出错: ${refreshGigaResourcePermissionResult.msg}`);
  }
}

// 获取 giga 资源包,需要处理风控的问题
export async function getGigaResource(gigaProductId: string) {
  try {
    const blob: Blob = await downloadGigaResource(gigaProductId);
    if (blob.type !== 'application/octet-stream') {
      if (blob.type === 'text/html') {
        const html = await blob.text();
        const match = html.match(/arg1\s*=\s*'([^']+)'/);
        // 如果返回的是 arg1 页面进行增加 cookie 处理
        if (match && match[1]) {
          const arg1 = match[1];
          console.log(arg1);
          const acwScV2 = getAcwScV2(arg1);
          console.log('acwScV2', acwScV2);
          // 更新 cookie
          await updateGigaAcwScV2CookieLocal(acwScV2);
          return getGigaResource(gigaProductId);
        } else {
          throw new Error(`受到封控策略限制导致无法获取到资源包,策略类型为验证码`);
        }
      } else if (blob.type === 'application/json') {
        throw new Error(`请先登录到 gigab2b 网站`);
      } else {
        throw new Error(`受到封控策略限制导致无法获取到资源包`);
      }
    } else {
      return blob;
    }
  } catch (error) {
    // if (error instanceof Error && error.message.match(/Network\s*Error/i)) {
    //   // 先进行权限更新
    //   // 如果抛出了错误,那么会终止后续的操作,否则继续进行资源获取操作
    //   console.log('出现了资源包权限获取错误', error);
    //   await refreshGigaResourcePermission({
    //     gigaProductId,
    //   });
    //   return getGigaResource(gigaProductId);
    // } else {
    //   throw new Error(`获取资源包失败: ${(error as Error).message}`);
    // }
    throw new Error(`获取资源包失败: ${(error as Error).message}`);
  }
}

// 处理验证码的问题
export async function handleGigaCaptchaByProxy() {
  const proxySettings = useProxyStore.getState();
  const proxyList = proxySettings.proxyList;
  const proxyToggleInterval = proxySettings.proxyToggleInterval;
  const currentProxy = proxySettings.currentProxy;
  return new Promise(async (resolve, reject) => {
    // const prevProxyConfig = await browser.runtime.sendMessage({
    //   type: MessageType.getProxy,
    // });

    // 延迟一定的时间间隔再设置代理,这样可以保证并发的请求都使用同一个新的代理
    setTimeout(async () => {
      // console.log(proxyToggleInterval);
      const proxyUrls = getProxyUrls(proxyList);
      // let prevUrl = '';
      // if (prevProxyConfig.data.mode === 'direct') {
      //   prevUrl = config.proxyDirectLabel;
      // }
      // if (prevProxyConfig.data.mode === 'fixed_servers') {
      //   const singleProxy = prevProxyConfig.data.rules.singleProxy;
      //   prevUrl = `${singleProxy.scheme}://${singleProxy.host}:${singleProxy.port}`;
      // }
      const index = proxyUrls.indexOf(currentProxy);
      if (index === -1) {
        // reject(new Error(`代理设置错误,没有找到匹配前一个代理的代理设置`));
        // 如果没有匹配的代理,那么也是返回第一个
      }
      let nextIndex = index + 1;
      // 如果越界了,那么返回第一个
      if (nextIndex === proxyUrls.length) {
        nextIndex = 0;
      }
      const nextUrl = proxyUrls[nextIndex];
      if (nextUrl === config.proxyDirectLabel) {
        await setProxyDirect();
      } else {
        const UrlObj = new URL(nextUrl);
        // await setProxyFixedServers({
        //   scheme: UrlObj.protocol.replace(':', ''),
        //   host: UrlObj.hostname,
        //   port: +UrlObj.port,
        // });
        await setProxyPAC(
          {
            host: UrlObj.hostname,
            port: +UrlObj.port,
          },
          ['www.gigab2b.com'],
        );
      }
      console.log(`代理转变: ${currentProxy} -> ${nextUrl}`);
      useProxyStore.dispatch({
        type: 'update',
        update(state) {
          state.currentProxy = nextUrl;
        },
      });
      resolve(void 0);
    }, proxyToggleInterval);
  });
}

export async function handleGigaCaptchaByPython(productId: string) {
  toast.info('连接 python 破解验证码服务中...');
  const res = await browser.runtime.sendMessage({
    type: MessageType.solveGigaCaptcha,
    data: {
      gigaProductId: productId,
    },
  });
  if (res.code === 0) {
    toast.success('成功破解验证码');
    return true;
  } else {
    toast.error('破解验证码失败');
    return false;
  }
}

// 获取 giga 产品的库存和价格,并且需要处理风控的问题
export async function getProductPrice(gigaProductId: string) {
  const proxySettings = useProxyStore.getState();
  const useProxyWhenGetGigaAvaliable = proxySettings.useProxyWhenGetGigaAvaliable;
  const result = await getProductPriceInfo(gigaProductId);
  if (typeof result === 'string') {
    const match = (result as string).match(/arg1\s*=\s*'([^']+)'/);
    if (match && match[1]) {
      // 处理 acw_sc__v2 反调脚本
      const arg1 = match[1];
      const acwScV2 = getAcwScV2(arg1);
      console.log('acwScV2', acwScV2);
      // 像 background 环境是没有 document 的
      if (typeof document !== 'undefined') {
        const href = document.location.href;
        if (href.startsWith('chrome-extension')) {
          await updateGigaAcwScV2CookieExtension(acwScV2);
        } else {
          await updateGigaAcwScV2CookieLocal(acwScV2);
        }
      } else {
        await updateGigaAcwScV2CookieExtension(acwScV2);
      }
      return getProductPrice(gigaProductId);
    }
    if ((result as string).match(/<title>Safe\s*Checker<\/title>/)) {
      if (useProxyWhenGetGigaAvaliable) {
        await handleGigaCaptchaByProxy();
      } else {
        await handleGigaCaptchaByPython(gigaProductId);
      }
      return getProductPrice(gigaProductId);
      // throw new Error('因为验证码问题导致脚本获取失败');
    }
  }
  if (!result.data.qty_visible) {
    // 如果是不可用产品,那么把库存设置为 0
    const baseProductInfo = await getProductBaseInfo(gigaProductId);
    if (baseProductInfo.code === 200) {
      if (baseProductInfo) {
        const isProductAvailable = baseProductInfo.data.product_info.is_product_available;
        if (!isProductAvailable) {
          result.data.qty_visible = true;
          // @ts-ignore
          result.data.quantity = {
            quantity: 0,
          };
        }
      }
    }
  }
  return result;
}

// 读取产品在 gigab2b 中的信息,主要用于给 temu 提供必要的信息
export async function getGigaProductBaseInfo(gigaProductId: string) {
  let non_sellable_platform: string[] = [];
  try {
    const productDetialInfo = await getProductBaseInfo(gigaProductId);
    if (productDetialInfo.code !== 200) {
      throw new Error(productDetialInfo.msg);
    }
    non_sellable_platform = productDetialInfo.data.product_info.non_sellable_on_full_list.map(
      (item) => {
        // 统一转化为小写
        return item.platform_name.toLowerCase();
      },
    );
  } catch (error) {
    console.log(error);
    toast.error(`获取 giga 的基础产品信息失败: ${(error as Error).message}`);
  }
  return {
    non_sellable_platform,
  };
}

// 解析 Characteristic featrue
export function parseCharacteristic(characteristic: string): string[] {
  if (!characteristic) {
    return [];
  } else {
    const feature: string[] = [];
    const div = document.createElement('div');
    div.innerHTML = characteristic;
    div.querySelectorAll('li').forEach((li) => {
      if (li.textContent) {
        feature.push(li.textContent);
      }
    });
    return feature;
  }
}

export function parseDescription(description: string): {
  name: string;
  value: string;
}[] {
  if (!description) {
    return [];
  } else {
    const descriptionObj: {
      name: string;
      value: string;
    }[] = [];
    const div = document.createElement('div');
    div.innerHTML = description;
    div.querySelectorAll('table tr').forEach((tr) => {
      if (
        tr.querySelector('td:nth-child(1)')?.textContent &&
        tr.querySelector('td:nth-child(2)')?.textContent
      ) {
        descriptionObj.push({
          name: tr.querySelector('td:nth-child(1)')?.textContent || '',
          value: tr.querySelector('td:nth-child(2)')?.textContent || '',
        });
      }
    });
    return descriptionObj;
  }
}

// 通过货号跳转到 giga 产品页面
export function gotoGigaProductPage(skuInfo: string) {
  const [gigaSku, gigaProductId] = getGigaSkuAndProductId(skuInfo);
  window.open(
    `https://www.gigab2b.com/index.php?route=product/product&product_id=${gigaProductId}`,
  );
}

// 计算产品的总价格
export function getProductTotalPrice(getProductPriceInfoResult: GetProductPriceInfoResult) {
  const basePrice = (getProductPriceInfoResult.data?.base_price_info?.price || 0) * 100;

  // 如果无法获取基础价格,那么返回 -1000 * 100
  if (basePrice === 0) {
    return config.NotFoundBaseGigaProductPrice * 100;
  }

  const fulfillmentPrice =
    (getProductPriceInfoResult.data?.fulfillment_options?.drop_ship?.total_amount || 0) * 100;
  return basePrice + fulfillmentPrice;
}

// 根据货号目录读取产品的采集状态
// export async function getProductColectState(
//   stateFilename: string,
//   directorHandle: FileSystemDirectoryHandle,
// ): Promise<CollectState> {
//   try {
//     const infoFileHandle = await directorHandle.getFileHandle(stateFilename, {
//       create: false,
//     });
//     const infoFile = await infoFileHandle.getFile();
//     // 读取文件中的 state 属性
//     const text = await infoFile.text();
//     try {
//       const state = JSON.parse(text);
//       return state[StateType.collect];
//     } catch (error) {
//       return CollectState.init;
//     }
//   } catch (error) {
//     return CollectState.init;
//   }
// }

// // 根据货号目录设置产品的采集状态
// export async function setProductCollectState(
//   state: CollectState,
//   stateFilename: string,
//   directorHandle: FileSystemDirectoryHandle,
// ) {
//   const infoFileHandle = await directorHandle.getFileHandle(stateFilename, {
//     create: true,
//   });
//   const infoFile = await infoFileHandle.getFile();
//   const text = await infoFile.text();
//   let info = {} as { [StateType.collect]: CollectState };
//   try {
//     info = JSON.parse(text);
//     info[StateType.collect] = state;
//   } catch (error) {
//     info = {
//       [StateType.collect]: state,
//     };
//   }
//   const writable = await infoFileHandle.createWritable();
//   await writable.write(JSON.stringify(info));
//   await writable.close();
// }
